package com.broada.apm.template.impl;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.broada.apm.model.Dimension;
import com.broada.apm.template.DimensionDataDictFetch;
import com.broada.apm.template.ResourceTemplate;
import com.broada.apm.template.RuleMatchEstimate;
import com.broada.apm.template.model.DimensionExt;
import com.broada.apm.template.model.DimensionRule;

/**
 * 默认json文件格式的数据字典抽取实现
 * @author jianfei.xu
 * @date   2016年3月17日
 *
 * @param <T>
 */
public class DefaultJsonDimensionDataDictFetch<T extends Dimension> implements DimensionDataDictFetch<T> {
	
	/**
	 * 构造函数
	 * @param jsonPath		:json文件位置
	 */
	public DefaultJsonDimensionDataDictFetch(String jsonPath) {
		this.jsonPath = jsonPath;
	}
	
	/**
	 * 数据字典数据抽取
	 * @param entityClass	:字节码
	 * @return		        :返回抽取的数据
	 */
	@Override
	public List<DimensionRule<T>> fetchData(Class<T> entityClass) {
		ResourceTemplate<DimensionExt> resTemplate = new DefaultJsonResourceTemplate<DimensionExt>(jsonPath);
		List<DimensionExt> rawDatList = resTemplate.getAll(DimensionExt.class); //原始数据
		if(null == rawDatList || 0 == rawDatList.size()) return null;
		Collections.sort(rawDatList, new Comparator<DimensionExt>() {//排序(从大到小)
			@Override
			public int compare(DimensionExt arg0, DimensionExt arg1) {
				return arg1.getOrder() - arg0.getOrder();
			}
		});
		
		List<DimensionRule<T>> dimensionRuleList = new LinkedList<DimensionRule<T>>();
		RuleMatchEstimate tmpRuleMatchEsti = null;
		T tmpEntity = null;
		for(DimensionExt tmpDime : rawDatList) {//数据加工
			tmpRuleMatchEsti = new DefaultRuleMatchEstimate(tmpDime.getRules());
			try {
				tmpEntity = entityClass.newInstance();
			} catch (InstantiationException | IllegalAccessException e) {
				LOG.error("反射动态生成对象失败", e);
				continue;
			}
			copyProperties(tmpDime, tmpEntity);
			dimensionRuleList.add(new DimensionRule<T>(tmpEntity, tmpRuleMatchEsti));
		}
		
		return dimensionRuleList;
	}
	
	/**
	 * 拷贝属性
	 * @param fromEntity	:源对象
	 * @param toEntity		:目标对象
	 */
	private void copyProperties(DimensionExt fromEntity, T toEntity) {
		toEntity.setId(fromEntity.getId());
		toEntity.setCode(fromEntity.getCode());
		toEntity.setName(fromEntity.getName());
		toEntity.setOrder(fromEntity.getOrder());
		toEntity.setSource(fromEntity.getSource());
		toEntity.setType(fromEntity.getType());
	}
	
	private String jsonPath; //json位置
	
	private static Logger LOG = LoggerFactory.getLogger(DefaultJsonDimensionDataDictFetch.class);
	
}
